package GenerateMain;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import org.junit.Test;

/**
 * 
 * @author liwei
 * 
 */
public class Generate {
	static ArrayList<String> filelist = new ArrayList<String>();
 public static  void main(String [] args){
service();
serviceImpl();
 }
	public void dao() {
		gen("dao.ftl", "Dao","D://templete_gen//dao");
	}
	public void daoImpl() {
		gen("daoImpl.ftl", "DaoImpl","D://templete_gen//dao//impl");
	}
	public  static  void service() {
		gen("interface.ftl", "Service","D:\\templete_gen\\interface");
	}
	public static void serviceImpl() {
		gen("serviceImpl.ftl", "ServiceImpl","D:\\templete_gen\\service\\impl");
	}
	public static void gen(String fileName, String classNameSp,String genPath) {
		try {
			String filePath = "D:/domain";
			getFiles(filePath);
			Writer out = null;
			String targetDir = genPath;
			File dir = new File(targetDir);
			if (!dir.isDirectory()) {
				dir.mkdirs();
			}
			Configuration cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File("src"));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			Template tpl = cfg.getTemplate(fileName);

			for (String name : filelist) {
				out = new FileWriter(new File(targetDir + "/" + name
						+ classNameSp + ".java"));
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("name", name);
				tpl.process(data, out);
			}
			out.flush();
			out.close();
		} catch (Exception e) {
		}

	}

	static void getFiles(String filePath) {
		File root = new File(filePath);
		File[] files = root.listFiles();
		System.out.println(files.length);
		for (File file : files) {
			String name = file.getName().split(".java")[0];
			System.out.println(name);
			filelist.add(name);
			System.out.println(file.getName());

		}
	}
}